Class Activation Map (MAP)


By Prof. Seungchul Lee
http://iai.postech.ac.kr/
Industrial AI Lab at POSTECH

Table of Contents

  • Attention

  • Visualizing and Understanding Convolutional Networks

1. CNN with a Fully Connected Layer¶

The conventional CNN can be conceptually divided into two parts. One part is feature extraction and the other is classification. In the feature extraction process, convolution is used to extract the features of the input data so that the classification can be performed well. The classification process classifies which group each input data belongs to by using the extracted features from the input data.

When we visually identify images, we do not look at the whole image; instead, we intuitively focus on the most important parts of the image. CNN learning is similar to the way humans focus. When its weights are optimized, the more important parts are given higher weights. But generally, we are not able to recognize this because the generic CNN goes through a fully connected layer and makes the features extracted by the convolution layer more abstract.



1.1. Issues on CNN (or Deep Learning)¶

  • Deep learning performs well comparing with any other existing algorithms
  • But works as a black box

    • A classification result is simply returned without knowing how the classification results are derived → little interpretability
  • When we visually identify images, we do not look at the whole image

  • Instead, we intuitively focus on the most important parts of the image
  • When CNN weights are optimized, the more important parts are given higher weights

  • Class activation map (CAM)

    • We can determine which parts of the image the model is focusing on, based on the learned weights
    • Highlighting the importance of the image region to the prediction



2. CAM: CNN with a Global Average Pooling¶

  • shed light on how it explicitly enables the convolutional neural network to have remarkable localization ability
  • the heatmap is the class activation map, highlighting the importance of the image region to the prediction

The deep learning model is a black box model. When input data is received, a classification result of 1 or 0 is simply returned for the binary classification problem, without knowing how the classification results are derived. Meanwhile, The class activation map (CAM) is capable of interpreting the results of the classification. We can determine which parts of the image the model is focusing on. Through an analysis of which part of the image the model is focusing on, we are able to interpret which part of the image is considered important.

The class activation map (CAM) is a modified convolution layer. It directly highlights the important parts of the spatial grid of an image. As a result, we can see the emphasized parts of the model. The below figure describes the procedure for class activation mapping.



The feature maps of the last convolution layer can be interpreted as a collection of visual spatial locations focused on by the model. The CAM can be obtained by taking a linear sum of the features. They all have different weights and thus can obtain spatial locations according to various input images through a linear combination. For a given image, $f_k(x,y)$ represents the feature map of unit $k$ in the last convolution layer at spatial location $(x,y)$. For a given class $c$, the class score, $S_c$, is expressed as the following equation.


$$S_c = \sum_k \omega_k^c \sum_{x,y} f_k(x,y)= \sum_{x,y} \sum_k \omega_k^c \; f_k(x,y)$$

where $\omega_k^c$ the weight corresponding to class $c$ for unit $k$. The class activation map for class $c$ is denoted as $M_c$.


$$M_c(x,y) = \sum_k \omega_k^c \; f_k(x,y)$$

$M_c$ directly indicates the importance of the feature map at a spatial grid $(x,y)$ of the class $c$. Finally the output of the softmax for class $c$ is,


$$P_c = \frac{\exp\left(S_c\right)}{\sum_c \exp\left(S_c\right)}$$

In case of the CNN, the size of the feature map is reduced by the pooling layer. By simple up-sampling, it is possible to identify attention image regions for each label.

3. CAM with NEU¶

Download data from here

InĀ [3]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import cv2
InĀ [4]:
x_train, x_test, y_train, y_test = np.load('./data_files/dataset.npy', allow_pickle = True)

n_train = x_train.shape[0]
n_test = x_test.shape[0]

print ("The number of training images : {}, shape : {}".format(n_train, x_train.shape))
print ("The number of testing images : {}, shape : {}".format(n_test, x_test.shape))
The number of training images : 1440, shape : (1440, 200, 200, 1)
The number of testing images : 360, shape : (360, 200, 200, 1)
InĀ [5]:
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(32, 
                           (3,3), 
                           activation='relu',
                           padding = 'SAME',
                           input_shape = (200, 200, 1)),
    tf.keras.layers.MaxPool2D((2,2)),
    tf.keras.layers.Conv2D(64, 
                           (3,3), 
                           activation = 'relu',
                           padding = 'SAME',
                           input_shape = (100, 100, 32)),
    tf.keras.layers.MaxPool2D((2,2)),
    tf.keras.layers.Conv2D(64, 
                           (3,3), 
                           activation = 'relu',
                           padding = 'SAME',
                           input_shape = (50, 50, 64)),
    tf.keras.layers.MaxPool2D((2,2)),
    tf.keras.layers.Conv2D(64, 
                           (3,3), 
                           activation = 'relu',
                           padding = 'SAME',
                           input_shape = (25, 25, 64)),
    tf.keras.layers.GlobalAveragePooling2D(),
    tf.keras.layers.Dense(6, activation = 'softmax', use_bias = False)
])
WARNING:tensorflow:From c:\users\seungchul lee\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\ops\init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
InĀ [6]:
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 200, 200, 32)      320       
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 100, 100, 32)      0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 100, 100, 64)      18496     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 50, 50, 64)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 50, 50, 64)        36928     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 25, 25, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 25, 25, 64)        36928     
_________________________________________________________________
global_average_pooling2d (Gl (None, 64)                0         
_________________________________________________________________
dense (Dense)                (None, 6)                 384       
=================================================================
Total params: 93,056
Trainable params: 93,056
Non-trainable params: 0
_________________________________________________________________



InĀ [7]:
model.compile(optimizer = 'adam', 
              loss = 'sparse_categorical_crossentropy', 
              metrics = ['accuracy'])
InĀ [8]:
model.fit(x_train, y_train,  epochs = 15)
Epoch 1/15
1440/1440 [==============================] - 32s 22ms/sample - loss: 1.7532 - acc: 0.2132
Epoch 2/15
1440/1440 [==============================] - 33s 23ms/sample - loss: 1.3260 - acc: 0.4465
Epoch 3/15
1440/1440 [==============================] - 33s 23ms/sample - loss: 0.8716 - acc: 0.6479
Epoch 4/15
1440/1440 [==============================] - 37s 26ms/sample - loss: 0.6331 - acc: 0.7639
Epoch 5/15
1440/1440 [==============================] - 38s 26ms/sample - loss: 0.5673 - acc: 0.7958
Epoch 6/15
1440/1440 [==============================] - 38s 26ms/sample - loss: 0.5590 - acc: 0.7833
Epoch 7/15
1440/1440 [==============================] - 41s 29ms/sample - loss: 0.4544 - acc: 0.8181
Epoch 8/15
1440/1440 [==============================] - 40s 28ms/sample - loss: 0.3789 - acc: 0.8556
Epoch 9/15
1440/1440 [==============================] - 37s 26ms/sample - loss: 0.3647 - acc: 0.8625
Epoch 10/15
1440/1440 [==============================] - 36s 25ms/sample - loss: 0.3658 - acc: 0.8646
Epoch 11/15
1440/1440 [==============================] - 36s 25ms/sample - loss: 0.3148 - acc: 0.8882
Epoch 12/15
1440/1440 [==============================] - 36s 25ms/sample - loss: 0.3200 - acc: 0.8785
Epoch 13/15
1440/1440 [==============================] - 37s 26ms/sample - loss: 0.3367 - acc: 0.8729
Epoch 14/15
1440/1440 [==============================] - 38s 27ms/sample - loss: 0.3257 - acc: 0.8785
Epoch 15/15
1440/1440 [==============================] - 36s 25ms/sample - loss: 0.3694 - acc: 0.8597
Out[8]:
<tensorflow.python.keras.callbacks.History at 0x29333559668>
InĀ [9]:
# accuracy test
x_test_loss, x_test_acc = model.evaluate(x_test,  y_test, verbose=2)
print('loss = {}, Accuracy = {} %'.format(round(x_test_loss,8), round(x_test_acc * 100)))
360/360 - 3s - loss: 0.3694 - acc: 0.8750
loss = 0.36944742, Accuracy = 88.0 %
InĀ [10]:
# get max pooling layer and fully connected layer 
weights =np.asarray(model.get_weights())
conv_layer = model.get_layer(index = 6)
fc_layer = weights[8]

# Class activation map 
x = tf.matmul(conv_layer.output, fc_layer)
CAM = tf.keras.Model(inputs = model.inputs, outputs = x)
InĀ [16]:
test_idx = np.random.choice(x_test.shape[0], 1)
test_image = x_test[test_idx].astype(np.float32)
result = CAM.predict(test_image)
pred = np.argmax(model.predict(test_image), axis = 1)
result = np.asarray(result)[0]

attention = result[:,:,pred]
attention = np.abs(np.reshape(attention,(25,25)))

large_test_x = cv2.resize(test_image.reshape(200,200), (200*5, 200*5))
large_attention = cv2.resize(attention, 
                             (200*5, 200*5), 
                             interpolation = cv2.INTER_CUBIC)

plt.figure(figsize = (10,15))
plt.subplot(3,2,1)
plt.imshow(x_test[test_idx].reshape(200,200), 'gray')
plt.axis('off')

plt.subplot(3,2,2)
plt.imshow(attention)
plt.axis('off')

plt.subplot(3,2,3)
plt.imshow(large_test_x, 'gray')
plt.axis('off')

plt.subplot(3,2,4)
plt.imshow(large_attention, 'jet', alpha = 0.5)
plt.axis('off')

plt.subplot(3,2,6)
plt.imshow(large_test_x, 'gray')
plt.imshow(large_attention, 'jet', alpha = 0.5)
plt.axis('off')
plt.show()
InĀ [12]:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')